package com.example.demojdbc.dao.impl;

import com.example.demojdbc.dao.UserDao;
import com.example.demojdbc.model.User;
import jakarta.annotation.Resource;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    // 新增一条用户
    @Override
    public int addUser(User user) {
        String sql = "INSERT INTO `user` (`user`.user_name,`user`.`status`) VALUES (?,?);";
        int update = jdbcTemplate.update(sql, user.getUserName(), user.getStatus());
        return update;
    }

    // 更新指定用户名的状态信息
    @Override
    public int update(User user) {
        String sql = "UPDATE `user` SET status = ? WHERE user_name = ?;";
        return jdbcTemplate.update(sql, user.getStatus(), user.getUserName());
    }

    // 删除指定用户名的用户
    @Override
    public int delete(User user) {
        String sql = "DELETE FROM `user` WHERE user_name =?;";
        return jdbcTemplate.update(sql, user.getUserName());
    }

    // 统计某种状态的用户数量
    @Override
    public int count(User user) {
        String sql = "SELECT COUNT(*) FROM `user` WHERE `status`=?;";
        return jdbcTemplate.queryForObject(sql, Integer.class, user.getStatus());
    }

    // 获取某种状态的用户列表
    @Override
    public List<User> getList(User user) {
        String sql = "SELECT * FROM `user` WHERE `status`=?;";
         return jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class), user.getStatus());
    }

    // 查询指定id的用户
    @Override
    public User getUser(User user) {
        String sql = "SELECT * FROM `user` where `user_id`=?;";
        return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), user.getStatus());
    }

    // 批量增加用户
    @Override
    public void batchAddUser(List<Object[]> batchArgs) {
        String sql = "INSERT INTO `user` (`user`.user_name,`user`.`status`) VALUES (?,?);";
        jdbcTemplate.batchUpdate(sql, batchArgs);
    }

}
